#!/usr/bin/env python
#coding: utf-8
"""
Management utility for deploy current django project with hg.
"""

import os, sys

from django.core.management.base import BaseCommand, CommandError

from common import settings

class Command(BaseCommand):
    
    help = 'Used to grunt the frontend static files to tmp static dir path'
    
    GRUNT_PACKAGE_JSON = '''{
          "name": "auoffice",
          "version": "0.1.0",
          "devDependencies": {
          }
        }
    '''
    
    def handle(self, grunt_cmd=None, **options):
        
        # 检查grunt功能是否开启
        if not settings.GRUNT_ON:
            raise CommandError('Please turn on the grunt in the project settings with "GRUNT_ON=True".')
        
        if grunt_cmd != 'test':
            grunt_cmd = 'publish'
        
        sys.stdout.write("Start to grunt frontend static files.\n")
        
        # 判断package.json文件是否存在, 不存在则根据GRUNT_PACKAGE_JSON模版创建
        package_fpath = os.path.join(settings.STATIC_GRUNT_ROOT, 'package.json')
        if not os.path.exists(package_fpath):
            f = file(package_fpath, 'w+')
            f.write(self.GRUNT_PACKAGE_JSON)
            f.close()
        
        # 备份当前的程序运行目录
        backup_cwd = os.getcwd()
        
        # 改变当前运行目录
        new_cwd = settings.STATIC_GRUNT_ROOT
        os.chdir(new_cwd)
        
        # 运行grunt
        status = os.system('grunt %s' % grunt_cmd)
        # 恢复程序运行时目录
        os.chdir(backup_cwd)
        if status != 0:
            raise CommandError('Grunt in %s failed.\n' % new_cwd)
          
        sys.stdout.write('Grunt static files finish, you can run "python manage collectstatic" to collect the static files.\n')
